﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web_uchet.Security.Enums;
using web_uchet.Security.Interfaces;
using web_uchet.ViewModels;
using web_uchet.Security;
using System.Net.Mail;
using Mvc.Validation;
using web_uchet.Classes.Payment;

namespace web_uchet.Controllers
{
    public class HomeController : MasterPageController
    {
         public HomeController()
            : this(null)
        {
        }

         public HomeController(IUserOperationsProvider Provider)
            : base(Provider)
        {
            
        }
         //public ActionResult LogOn()
         //{
         //    return View();
         //}

         //[AcceptVerbs(HttpVerbs.Post)]
         public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
         {
             LoginResult LogRes = this._UserOperationProvider.LoginUser(userName, password, rememberMe);
             switch (LogRes)
             {
                 case LoginResult.Success:
                     return RedirectToAction("Index", "Home");
                     break;
                 case LoginResult.LowAccount:
                     return RedirectToAction("Index", "Home");
                     break;
                 case LoginResult.Fail:
                     return RedirectToAction("Index", "Home");
                     break;
                 default:
                     return RedirectToAction("Index", "Home");
                     break;
             }
         }
         
        [AcceptVerbs(HttpVerbs.Get)]
         public ActionResult LogOff()
         {
             this._UserOperationProvider.LogOut();
             return RedirectToAction("Index");
         }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult StartWork()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult feedback()
        {
            return View(new web_uchet.Classes.Feedback());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult feedback(web_uchet.Classes.Feedback Data)
        {
            try
            {   
                Data.Validate();
                //MailMessage Mail = new MailMessage();
                //Mail.Body=Data.Text+ "\nFrom: "+Data.FeedbackMail;
                //Mail.From = //new MailAddress("support@web-uchet.ru");
                //    new MailAddress(Data.FeedbackMail);
                //Mail.To.Add(new MailAddress("support@web-uchet.ru"));
                //Mail.Subject = Data.Subject;
                //// Set the format of the mail message body as HTML
                //Mail.IsBodyHtml = true;
                //// Set the priority of the mail message to normal
                //Mail.Priority = MailPriority.Normal;
                ////Send the message.
                //SmtpClient client = new SmtpClient();

                //client.Send(Mail);
                System.Web.Mail.MailMessage m = new System.Web.Mail.MailMessage();
                m.From = Data.FeedbackMail;
                m.To = "support@web-uchet.ru";
                m.Subject = Data.Subject;
                m.Body = Data.Text;
                m.BodyFormat = System.Web.Mail.MailFormat.Text;
                m.BodyEncoding = System.Text.Encoding.UTF8;// GetEncoding("windows-1251");

                System.Web.Mail.SmtpMail.SmtpServer = "robots.1gb.ru";
                System.Web.Mail.SmtpMail.Send(m);

                return View("Success");                           
            }
            catch (EntityValidationException ex)
            {
                ViewData.ModelState.PopulateWithErrors(ex);
                return View(Data);
            }
            //catch (Exception)
            //{
            //    throw new Exception("Не удалось отправить сообщение");
            //} 
        }

        public ActionResult Information()
        {
            return View();
        }

        public ActionResult TargetBusiness()
        {
            return View();
        }
        public ActionResult ChoiceHelp()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Payment(Payment Data)
        {
            if (this.Request.IsAjaxRequest())
            {
                ViewКомпания Company = this._UserOperationProvider.GetUsersCompany(Data.UserName, Data.PW);
                if (Company!=null)
                {
                    Data.InitNew();
                    Data.CompanyID=Company.ИД_Компании;
                    Data.CompanyName=Company.Название;
                    Data.s_order_id = Company.ИД_Компании.ToString();
                    //Data.s_order_id=(new Random(234)).Next().ToString();
                    Data.s_sign=Data.GetIndexSign();
                    //Стереть некоторые поля для безопасности
                    Data.CompanyName = string.Empty;
                    Data.PW = string.Empty;
                    Data.UserName = string.Empty;
                    Data.secret_code= string.Empty;
                    return Json(Data,JsonRequestBehavior.AllowGet);
                }
                return Json(new { Error = "Компания не распознана, т.к. введено неверное имя пользователя или пароль" }
                    ,JsonRequestBehavior.AllowGet);
            }
            else
            {
                Payment NewPayment = new Payment();
                //NewPayment.InitNew();
                return View(NewPayment);
            }
        }

        public ActionResult paymentsuccess(Payment Data)
        {
            return View("Success");
        }

        public ActionResult paymentresult(Payment Data)
        {
            Data.InitNew();
            if (Data.s_sign_v2 == Data.GetResultSign())
            {                
                this._UserOperationProvider.SetCompanyAccount(Data.CompanyID, Data.s_amount);
                Response.StatusCode = 200;
                return new EmptyResult();
            }
            else throw new System.Security.SecurityException("Исключение системы безопасности");
        }

        public ActionResult paymentfail(Payment Data)
        {
            return View("Error");
        }      

        
    }
}
